package com.adinnet.common.outbound.pay.utils;

import com.adinnet.common.utils.XMLUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class WXSignature {
    private static final Logger logger = LogManager.getLogger(WXSignature.class);

    /**
     * 生成签名
     *
     * @param characterEncoding
     * @param parameters
     * @param partnerKye
     * @return
     */
    public static String createSign(String characterEncoding, Map<String, String> parameters, String partnerKye) {
        String content = null;
        try {
            content = AlipaySignature.getSignCheckContentV(parameters, Boolean.FALSE).get("content");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        content += "&key=" + partnerKye;
        String sign = MD5Util.MD5Encode(content, characterEncoding).toUpperCase();
        System.out.println("\n生成签名\t"+sign);
        return sign;
    }

    /**
     * 处理订单结构
     *
     * @param parameters
     * @return
     */
    public static String getRequestXml(Map<String, String> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("sign".equalsIgnoreCase(k)) {

            } else if ("attach".equalsIgnoreCase(k)) {
            // } else if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("<" + "sign" + ">" + "" + parameters.get("sign") + "</" + "sign" + ">");
        // sb.append("<" + "sign" + ">" + "<![CDATA[" + parameters.get("sign") + "]]></" + "sign" + ">");
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 验证微信支付的签名
     * @param xmlString
     * @param weixinPartnerKey
     * @return
     */
    public static boolean verifySign(String xmlString , String weixinPartnerKey) {
        Map<String, String> map = null;
        try {
            map = XMLUtils.doXMLParse(xmlString);
        } catch (Exception e) {
            return false;
        }
        String signFromAPIResponse = map.get("sign").toString();
        if (signFromAPIResponse == "" || signFromAPIResponse == null) {
            logger.error(">>>>>>>>>>>"+"API返回的数据签名数据不存在，有可能被第三方篡改!!!");
            return false;
        }
        logger.error(">>>>>>>>>>"+"服务器回包里面的签名是:" + signFromAPIResponse);
        //清掉返回数据对象里面的Sign数据（不能把这个数据也加进去进行签名），然后用签名算法进行签名
        map.remove("sign");
        //将API返回的数据根据用签名算法进行计算新的签名，用来跟API返回的签名进行比较
        String signForAPIResponse = WXSignature.createSign("UTF-8" ,map , weixinPartnerKey);
        if (!signForAPIResponse.equals(signFromAPIResponse)) {
            //签名验不过，表示这个API返回的数据有可能已经被篡改了
            logger.error(">>>>>>>>>>>>>"+"API返回的数据签名验证不通过，有可能被第三方篡改!!! signForAPIResponse生成的签名为" + signForAPIResponse);
            return false;
        }
        logger.error(">>>>>>>>>>>>>"+"恭喜，API返回的数据签名验证通过!!!");
        return true;
    }
}
